<!--
 * @Author       : xiaoxiaoguai
 * @Date         : 2025-07-25 11:28:01
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2025-07-26 14:32:47
 * @Description  : 
-->
<template>
	<view class="container">
		<z-paging
			v-if="firstLoaded || isCurrentPage"
			ref="pagingRef"
			v-model="dataList"
			:enable-back-to-top="currentIndex === tabIndex"
			@scroll="scroll"
			@query="queryList"
			:paging-style="{ background: '#f5f5f5', paddingTop: '20rpx' }"
			:show-refresher-when-reload="true"
			:auto-show-back-to-top="true"
			:refresher-fps="0"
			:refresher-end-bounce-enabled="false"
			:refresher-default-duration="0"
			:refresher-complete-delay="150"
			refresher-pulling-text="松开刷新"
			refresher-default-text="再往下拉"
			:refresher-complete-duration="0"
			:refresher-refreshing-scrollable="false"
			:fixed="false">
			<template #top>
				<view class="my-couponType" v-if="currentIndex == 0">
					<scroll-view scroll-x >
						<view
							:class="{
								'my-couponType_item_active': currentCouponType == item.value,
							}"
							class="my-couponType_item"
							@click="setCouponType(item.value)"
							v-for="(item, index) in couponTypeList"
							:key="index">
							{{ item.label }}
						</view>
					</scroll-view>
				</view>
			</template>
			<!-- 自定义返回顶部view -->
			<!-- <template #backToTop>
				<custom-back-to-top ref="backToTop" :current="currentPage" :total="total" />
			</template> -->
			<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
			<view
				class="couponClass"
				v-for="(item, index) in dataList"
				:key="index"
				@click="openDetailModal(item, index)">
				<view class="taobao">
					<view class="ticket">
						<view class="typeInfoClass">
							{{ typeInfo(item.type) }}
						</view>
						<view class="sangleClass"></view>
						<view class="left">
							<image
								class="picture"
								v-if="item.image"
								:src="item.image"
								mode="aspectFill"></image>
							<view class="introduce">
								<view class="top">
									<view>满{{ item.least }}减{{ item.value }}</view>
								</view>
								<view class="type">{{ item.title }}</view>
								<view class="date u-line-1">
									{{ formatDateTime(item.startTime, 'yyyy-MM-dd') }}-{{
										formatDateTime(item.endTime, 'yyyy-MM-dd')
									}}
								</view>
							</view>
						</view>
						<view class="rightClass">
							<view class="moneyClass">
								<text>￥</text>
								<text class="big">{{ item.value }}</text>
							</view>
							<!-- 我的优惠券 -->
							<view v-if="currentIndex == 0" @click.stop="">
								<view
									v-if="item.statusName == '立即使用'"
									class="use immediate-use"
									:round="true"
									@tap="useCouponWith(item)">
									{{ item.statusName }}
								</view>
								<view
									v-else-if="
										item.statusName == '已使用' ||
										item.statusName == '已过期' ||
										item.statusName == '未开始'
									"
									class="used">
									{{ item.statusName }}
								</view>
							</view>
							<view v-if="currentIndex == 1" @click.stop="">
								<view class="use immediate-use" :round="true" @tap="receive(item)">
									立即领取
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</z-paging>
		<modal custom :show="detailModalVisible" @cancel="closeDetailModal" width="90%">
			<view class="modal-content">
				<view class="d-flex font-size-extra-lg text-color-base just-content-center mb-20">
					{{ coupon.title }}
				</view>
				<view class="d-flex font-size-sm text-color-base mb-20">
					有效期：{{ formatDateTime(coupon.startTime, 'yyyy-MM-dd') }}-{{
						formatDateTime(coupon.endTime, 'yyyy-MM-dd')
					}}
				</view>
				<view class="d-flex font-size-sm text-color-base mb-20">
					领取时间：{{ formatDateTime(coupon.createTime) }}
				</view>
				<view class="d-flex font-size-sm text-color-base mb-20">
					券价值：满{{ coupon.least }}减{{ coupon.value }}
				</view>
				<view class="d-flex font-size-sm text-color-base mb-20" v-if="currentIndex == 1">
					每人限领：{{ coupon.limit }} 张
				</view>
				<view class="d-flex font-size-sm text-color-base mb-20">
					适用范围：{{ typeInfo(coupon.type) }}
				</view>
				<view class="d-flex font-size-sm text-color-base mb-20">
					适用店铺：{{ coupon.shopName }}
				</view>
				<view
					class="d-flex align-items-center just-content-center"
					v-if="currentIndex == 0">
					<button type="primary" @tap="useCoupon" class="use-coupon-btn">立即使用</button>
				</view>
				<view
					class="d-flex align-items-center just-content-center"
					v-if="currentIndex == 1">
					<button type="primary" @tap="receive(coupon)" class="use-coupon-btn">
						立即领取
					</button>
				</view>
			</view>
		</modal>

		<!--轻提示-->
		<uv-toast ref="uToast"></uv-toast>
	</view>
</template>

<script setup>
	import { ref, watch, nextTick } from 'vue'
	import { useMainStore } from '@/store/store'
	import { storeToRefs } from 'pinia'
	import { onLoad, onShow, onPullDownRefresh, onHide } from '@dcloudio/uni-app'
	import { formatDateTime, kmUnit } from '@/utils/util'
	import { couponReceive, couponMine, couponIndexApi } from '@/api/coupon'
	const couponTypeList = ref([
		{ label: '全部', value: '' },
		{ label: '可使用', value: '0' },
		{ label: '已使用', value: '1' },
		{ label: '已过期', value: '2' },
		{ label: '未开始', value: '3' },
	])
	const currentCouponType = ref('')
	const main = useMainStore()
	const { isLogin } = storeToRefs(main)
	const props = defineProps({
		tabIndex: {
			type: Number,
			default: 0,
		},
		currentIndex: {
			type: Number,
			default: 0,
		},
		currentItem: {
			type: Object,
			default: () => {},
		},
	})
	const detailModalVisible = ref(false)
	const firstLoaded = ref(false)
	const dataList = ref([])
	const total = ref(0)
	const currentPage = ref(0)
	const coupon = ref({})
	const backToTop = ref()
	const scroll = () => {
		if (backToTop.value) {
			backToTop.value.isScroll()
		}
	}
	const uToast = ref()
	const isCurrentPage = ref(false)
	const pagingRef = ref(null)

	// 懒加载监听
	watch(
		() => props.currentIndex,
		newVal => {
			if (newVal === props.tabIndex) {
				console.log('滚动到当前页')
				if (!firstLoaded.value) {
					nextTick(() => {
						setTimeout(() => {
							isCurrentPage.value = true
						}, 100)
					})
				}
			}
		},
		{ immediate: true }
	)
	const setCouponType = e => {
		currentCouponType.value = e
		reload()
	}
	// 刷新列表方法
	const reload = () => {
		nextTick(() => {
			pagingRef.value?.reload()
		})
	}
	// 列表请求函数（z-paging会自动调用）
	const queryList = async (pageNo, pageSize) => {
		currentPage.value = pageNo
		try {
			let dataListCopy = []
			if (props.currentIndex == 0) {
				dataListCopy = await couponMine({
					page: pageNo,
					pagesize: pageSize,
					status: currentCouponType.value,
				})
			} else if (props.currentIndex == 1) {
				dataListCopy = await couponIndexApi({
					page: pageNo,
					pagesize: pageSize,
				})
			}
			setTimeout(() => {
				console.log(dataListCopy)
				pagingRef.value?.complete(dataListCopy)
				firstLoaded.value = true
				// total.value = dataListCopy.total
			}, 200)
		} catch (err) {
			pagingRef.value?.complete(false)
		}
	}

	const typeInfo = type => {
		if (type == 0) {
			return '通用'
		}
		if (type == 1) {
			return '自取'
		}
		if (type == 2) {
			return '外卖'
		}
		if (type == 3) {
			return '堂食'
		}
	}
	const openDetailModal = (couponCopy, index) => {
		coupon.value = couponCopy
		detailModalVisible.value = true
	}
	const useCouponWith = coupon => {
		useCoupon()
	}
	const closeDetailModal = () => {
		detailModalVisible.value = false
		coupon.value = {}
	}
	const useCoupon = () => {
		uni.switchTab({
			url: '/pages/home/menu',
		})
	}

	// 领取优惠券
	const receive = async coupon => {
		let data = await couponReceive({ id: coupon.id })
		if (data) {
			uToast.value.show({
				message: '领取成功',
				type: 'success',
			})
			detailModalVisible.value = false
		}
	}
	// 暴露方法给父组件调用
	defineExpose({
		reload,
	})
</script>

<style lang="scss" scoped>
	/* #ifdef H5 */
	page {
		height: 100%;
	}
	/* #endif */

	.container {
		height: 100%;
	}
	.my-couponType {
		padding: 0 20rpx;
		margin-bottom: 20rpx;
        white-space: nowrap;
		.my-couponType_item {
			display: inline-block;
			color: #000;
			border-radius: 120rpx;
			font-size: 28rpx;
			padding: 8rpx 26rpx;
			border: 2rpx solid #fff;
			margin-left: 20rpx;
			background-color: #fff;
			&:first-child {
				margin-left: 0;
			}
		}
		.my-couponType_item_active {
			color: $qingzhen-btn-primary-color;
			border: 2rpx solid $qingzhen-btn-primary-color;
		}
	}
	.couponClass {
		display: flex;
		flex-direction: column;
		background-color: #ffffff;
		margin: 0 20rpx 30rpx 20rpx;
		box-shadow: 0 10rpx 10rpx -10rpx rgba(15, 15, 15, 0.3);
		position: relative;
		&::before {
			content: '';
			position: absolute;
			background-color: $bg-color;
			width: 30rpx;
			height: 30rpx;
			bottom: 65rpx;
			left: -15rpx;
			border-radius: 100%;
		}

		&::after {
			content: '';
			position: absolute;
			background-color: $bg-color;
			width: 30rpx;
			height: 30rpx;
			bottom: 65rpx;
			right: -15rpx;
			border-radius: 100%;
		}

		.detail {
			padding: 20rpx 0;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				left: 0;
				right: 0;
				bottom: 0;
				border-bottom: 1rpx dashed #c6c6c6;
				transform: scaleY(0.5);
			}
		}
	}
	.use-coupon-btn {
		width: 95%;
		border-radius: 50rem !important;
	}

	.taobao {
		position: relative;
		overflow: hidden;
		background-color: white;
		.ticket {
			display: flex;
			.sangleClass {
				position: absolute;
				top: 0;
				right: 0;
				width: 0;
				height: 0;
				border-left: 72rpx solid transparent;
				border-bottom: 72rpx solid #ff4d4f;
				transform: rotate(-90deg);
			}
			.typeInfoClass {
				position: absolute;
				top: 10rpx;
				right: 2rpx;
				font-size: 22rpx;
				color: #fff;
				transform: rotate(45deg);
				z-index: 9;
			}
			.left {
				width: 70%;
				padding: 20rpx;
				background-color: white; //rgb(255, 245, 244);
				border-radius: 20rpx;
				border-right: dashed 2rpx rgb(224, 215, 211);
				display: flex;
				.picture {
					border-radius: 20rpx;
					width: 150rpx;
					margin-right: 20rpx;
					height: 150rpx;
				}
				.introduce {
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.top {
						color: $qingzhen-btn-primary-color;
						font-size: 36rpx;
					}
					.type {
						margin-top: 10rpx;
						font-size: 28rpx;
						color: $uv-info-dark;
					}
					.date {
						margin-top: 20rpx;
						font-size: 24rpx;
						color: $uv-info-dark;
					}
				}
			}
			.rightClass {
				width: 30%;
				padding: 30rpx 20rpx;
				background-color: white; //rgb(255, 245, 244);
				border-radius: 20rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				.moneyClass {
					margin-bottom: 10rpx;
					.big {
						font-size: 50rpx;
						font-weight: bold;
					}
				}

				.use {
					height: auto;
					padding: 0 20rpx;
					font-size: 24rpx;
					border-radius: 40rpx;
					color: #ffffff !important;
					background-color: $qingzhen-btn-primary-color !important;
					line-height: 40rpx;
					color: rgb(117, 142, 165);
				}
				.used {
					height: auto;
					padding: 0 20rpx;
					font-size: 24rpx;
					border-radius: 40rpx;
					line-height: 40rpx;
				}
			}
		}
	}
</style>
